// pages/auth/index.js
const app = getApp();
const api = app.api;
const wxutil = app.wxutil;

Page({
  data: {
    code: '',
    nickName: '',
    imageFiles: [], // 图片文件列表
  },

  onLoad() {
    this.getCode();
  },

  /**
   * 授权
   */
  getCode() {
    wx.login({
      success: (res) => {
        this.setData({
          code: res.code,
        });
      },
    });
  },

  setNickName(event) {
    const { value } = event.detail;
    this.setData({
      nickName: value,
    });
  },

  /**
   * 授权登录
   */
  auth() {
    const { code, nickName } = this.data;

    if (!wxutil.isNotNull(nickName)) {
      wx.lin.showMessage({
        type: 'error',
        content: '昵称不能为空！',
      });
      return;
    }

    wx.getUserProfile({
      desc: '授权用户信息将用于绑定用户',
      lang: 'zh_CN',
      success: (res) => {
        const { encryptedData, iv } = res;
        const app_id = app.globalData.appId;
        const data = {
          encrypted_data: encryptedData,
          iv,
          code,
          app_id,
          nickName,
        };

        wxutil.request
          .post(api.userAPI, data)
          .then((res) => {
            if (res.data.code === 200) {
              const userDetail = res.data.data;
              wxutil.setStorage('userDetail', userDetail, 86400 * 28);
              app.globalData.userDetail = userDetail;
              wx.lin.showMessage({
                type: 'success',
                content: '授权成功',
                success() {
                  wx.navigateBack();
                },
              });
            } else {
              wx.lin.showMessage({
                type: 'error',
                content: res.msg,
              });
            }
          })
          .catch((error) => {
            // 处理请求错误
            console.error('请求失败:', error);
          });
      },
      complete: () => {
        this.getCode();
      },
    });
  },

  onShareAppMessage() {
    return {
      title: '授权',
      path: '/pages/auth/index',
    };
  },
});
